package com.efounder.form.comp.sign;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.efounder.builder.base.data.DataSetEvent;
import com.efounder.builder.base.data.DataSetListener;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.form.DMColComponent;
import com.efounder.form.DMComponent;
import com.efounder.form.DataSetComponent;
import com.efounder.form.base.IComponent;
import com.efounder.form.comp.IUIComponent;
import com.efounder.form.model.JSONFormModel;
import com.efounder.form.util.CloudUtil;
import com.efounder.form.util.FormCompUtil;
import com.efounder.form.util.ReduseImageUtil;
import com.efounder.frame.ViewSize;
import com.efounder.imageloader.GlideImageLoader;
import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;
import com.efounder.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import static com.efounder.form.util.FormCompUtil.getLayoutGravity;
import static com.efounder.form.util.ReduseImageUtil.chatpath;


/**
 * Created by XinQing on 2016/9/28.
 * 签名组件
 */

public class FormSign extends LinearLayout implements View.OnKeyListener, IComponent, IUIComponent, DMComponent, DMColComponent, DataSetListener {

    //原生空件
    private SignListener signListener;
    private PopupWindow popupWindow;
    private ImageView signImage;
    private GraffitiView graffitiView;
    //平台view
    private String horizontalAlign;
    private String verticalAlign;
    private String id;
    private int height;
    private int width;
    private int gap = 0;
    private ViewSize size = new ViewSize(0, 0);
    private int percentWidth;
    private int percentHeight;
    private int bkgColor;
    //平台数据
    private String dataSetID;
    private String dataSetColID;
    private DataSetComponent dataSetComponent;
    private EFDataSet dataSet;
    private EFRowSet mainRowSet;

    private IUIComponent parentComp;


    public FormSign() {
        super(AppContext.getCurrentActivity());
        init();
    }

    public FormSign(Context context) {
        super(context);
        init();
    }

    public FormSign(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        signImage = new ImageView(getContext());
        LayoutParams signParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        signImage.setLayoutParams(signParams);
        signImage.setImageDrawable(getResources().getDrawable(R.drawable.form_sign_icon));
//        signImage.setScaleType(ImageView.ScaleType.FIT_XY);
        signImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow();
            }
        });
        addView(signImage);
        //默认LayoutParams
        int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 110, getResources().getDisplayMetrics());
        int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(width, height);
        setLayoutParams(layoutParams);
        //默认背景
        setBackgroundColor(Color.LTGRAY);
    }

    private void showPopupWindow() {
        if (popupWindow == null) {
            popupWindow = new PopupWindow(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            View contentView = createContentView4PopupWindow();
            popupWindow.setContentView(contentView);
            //处理返回键
//            popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
            popupWindow.setFocusable(true);
            contentView.setFocusable(true);
            contentView.setFocusableInTouchMode(true);
            contentView.setOnKeyListener(this);

        }
        popupWindow.showAtLocation(this, Gravity.CENTER, 0, 0);
    }

    private View createContentView4PopupWindow() {
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels / 4;
        int actionBarHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 39, getResources().getDisplayMetrics());

        //contentView
        LinearLayout contentView = new LinearLayout(getContext());
        //contentView.setBackgroundResource(R.drawable.add);
        //contentView.setBackgroundColor(getResources().getColor(android.R.drawable.dialog_holo_light_frame));

        contentView.setOrientation(LinearLayout.VERTICAL);
//        contentView.setBackgroundColor(0xFFAAAAAA);

        //涂鸦view
        graffitiView = new GraffitiView(getContext(), width, height);
        //graffitiView.setBackgroundColor(Color.YELLOW);
        contentView.addView(graffitiView);

        //actionBar
        //actionBar-container
        LinearLayout actionBarContainer = new LinearLayout(getContext());
        actionBarContainer.setOrientation(LinearLayout.HORIZONTAL);
        actionBarContainer.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        actionBarContainer.setPadding(5, padding, 0, padding);
        LayoutParams actionBarParam = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, actionBarHeight);
        actionBarContainer.setLayoutParams(actionBarParam);
        //actionBar-button
        LayoutParams buttonParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int buttonMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
        buttonParams.rightMargin = buttonMargin;
        //撤销
        Button button = new Button(getContext());
        button.setText("撤销");
        button.setTextSize(15);
        button.setTextColor(0xFFFFFFFF);
        button.setPadding(0, 0, 0, 0);
        button.setBackgroundColor(0xFFb00e11);
        button.setLayoutParams(buttonParams);
        actionBarContainer.addView(button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                graffitiView.undo();

            }
        });
        //清除
        button = new Button(getContext());
        button.setText("清除");
        button.setTextSize(15);
        button.setTextColor(0xFFFFFFFF);
        button.setPadding(0, 0, 0, 0);
        button.setBackgroundColor(0xFFb00e11);
        button.setLayoutParams(buttonParams);
        actionBarContainer.addView(button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                graffitiView.redo();

            }
        });
        //取消
        button = new Button(getContext());
        button.setText(R.string.common_text_cancel);
        button.setTextSize(15);
        button.setTextColor(0xFFFFFFFF);
        button.setPadding(0, 0, 0, 0);
        button.setBackgroundColor(0xFFb00e11);
        button.setLayoutParams(buttonParams);
        actionBarContainer.addView(button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (signListener != null) {
                    signListener.onCancel();
                }
                if (graffitiView.getSavePath().size() <= 0) {
                    if (mainRowSet != null)
                        mainRowSet.put(dataSetColID, "");
                }
            }
        });
        //确定
        button = new Button(getContext());
        button.setText(R.string.common_text_confirm);
        button.setTextSize(15);
        button.setTextColor(0xFFFFFFFF);
        button.setPadding(0, 0, 0, 0);
        button.setBackgroundColor(0xFFb00e11);
        button.setLayoutParams(buttonParams);
        actionBarContainer.addView(button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                graffitiView.saveToSDCard(Environment.getExternalStorageDirectory().getAbsolutePath());


                //上传图片到qiNiu
                final ProgressDialog progressDialog = new ProgressDialog(AppContext.getCurrentActivity());//ProgressDialog.show(getContext(),"请稍后...","正在上传");
                progressDialog.setMessage("正在验证签名...");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//                progressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                progressDialog.show();
                Bitmap bitmap = graffitiView.getBitmap();
                if (bitmap == null) return;
                byte[] data = Bitmap2Bytes(bitmap);

                //todo 20170428 yqs 修改云盘上传，先保存成文件
                String fileName = System.currentTimeMillis() + ".png";
                try {
                    ReduseImageUtil.saveFileToPNG(bitmap, fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String filePath = chatpath + fileName + ".pic";
                File signFile = new File(filePath);
                if (!signFile.exists()) {
                    Toast.makeText(getContext(), "签名上传验证失败，签名不存在", Toast.LENGTH_SHORT).show();
                    return;
                }

                CloudUtil.getCloudRes(filePath, new CloudUtil.UpLoadListenerWithProgress() {
                    @Override
                    public void getHttpUrl(Boolean isSuccess, String url) {
                        progressDialog.dismiss();
                        if (isSuccess) {
                            Bitmap bitmap = graffitiView.getBitmap();
                            if (bitmap != null) {
                                signImage.setImageBitmap(bitmap);
                            }
                            popupWindow.dismiss();
                            if (signListener != null) {
                                signListener.onComplete(bitmap);
                            }
                            if (mainRowSet == null) return;
                            if (graffitiView.getSavePath().size() <= 0) {
                                if (mainRowSet != null) {
                                    mainRowSet.put(dataSetColID, "");
                                }
                            } else {
                                mainRowSet.put(dataSetColID, url);

                            }
                        } else {
                            Toast.makeText(getContext(), "签名验证失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void getHttpProgress(int progress) {

                    }
                });

//七牛方式上传

//                QiNiuUtil.uploadQiNiuRes(data, new QiNiuUtil.UpLoadListener() {
//                    @Override
//                    public void getHttpUrl(Boolean isSuccess, String url) {
//                        progressDialog.dismiss();
//                        if (isSuccess) {
//                            Bitmap bitmap = graffitiView.getBitmap();
//                            if (bitmap != null) {
//                                signImage.setImageBitmap(bitmap);
//                            }
//                            popupWindow.dismiss();
//                            if (signListener != null) {
//                                signListener.onComplete(bitmap);
//                            }
//                            if (mainRowSet == null) return;
//                            if (graffitiView.getSavePath().size() <= 0) {
//                                if (mainRowSet != null) {
//                                    mainRowSet.put(dataSetColID, "");
//                                }
//                            } else {
//                                mainRowSet.put(dataSetColID, url);
//
//                            }
//                        } else {
//                            Toast.makeText(getContext(), "签名验证失败", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });

            }
        });

        contentView.addView(actionBarContainer);
        return contentView;
    }


    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            popupWindow.dismiss();
            return true;
        }
        return false;
    }


    public void setSignImageIcon(Drawable drawable) {
        signImage.setImageDrawable(drawable);
    }

    public ImageView getSignImage() {
        return signImage;
    }

    public SignListener getSignListener() {
        return signListener;
    }

    public void setSignListener(SignListener signListener) {
        this.signListener = signListener;
    }


    @Override
    public void creationComplete() {

    }

    @Override
    public void setLayout() {
        FormCompUtil.setLayoutSize(this);
        this.setGravity(getLayoutGravity(horizontalAlign, verticalAlign));
    }

    @Override
    public String getID() {
        return id;
    }

    @Override
    public void setID(String id) {
        this.id = id;
    }

    @Override
    public int getGap() {
        return gap;
    }

    @Override
    public void setGap(int gap) {
        this.gap = gap;
    }

    @Override
    public void setCompWidth(int width) {
        this.width = width;
    }

    @Override
    public int getCompWidth() {
        return this.width;
    }

    @Override
    public void setCompHeight(int height) {
        this.height = height;
    }

    @Override
    public int getCompHeight() {
        return this.height;
    }

    @Override
    public int getPercentWidth() {
        return percentWidth;
    }

    @Override
    public void setPercentWidth(int percentW) {
        percentWidth = percentW;
    }

    @Override
    public int getPercentHeight() {
        return percentHeight;
    }

    @Override
    public void setPercentHeight(int percentH) {
        percentHeight = percentH;
    }

    @Override
    public ViewSize getViewSize() {
        return size;
    }

    @Override
    public void setViewSize(ViewSize size) {
        this.size = size;
    }

    @Override
    public DataSetComponent getDataSetComponent() {
        return dataSetComponent;
    }

    @Override
    public void setDataSetComponent(DataSetComponent dsc) {
        if (dataSetComponent != null)
            dataSetComponent.removeDMComponent(this);
        dataSetComponent = dsc;
        if (dataSetComponent != null)
            dataSetComponent.insertDMComponent(this);
    }

    public void setDataSetComponent(JSONFormModel dsc) {
        if (dataSetComponent != null)
            dataSetComponent.removeDMComponent(this);
        dataSetComponent = dsc;
        if (dataSetComponent != null)
            dataSetComponent.insertDMComponent(this);
    }

    @Override
    public void setDataSetID(String dataSetID) {
        this.dataSetID = dataSetID;
    }

    @Override
    public String getDataSetColID() {
        return dataSetColID;
    }

    @Override
    public void setDataSetColID(String dataSetColID) {
        this.dataSetColID = dataSetColID;
    }

    @Override
    public String getDataSetNameColID() {
        return null;
    }

    @Override
    public void setDataSetNameColID(String s) {

    }

    @Override
    public String getInternalDataSetID() {
        return null;
    }

    @Override
    public void setInternalDataSetID(String s) {

    }

    @Override
    public void setViewDataSetID(String s) {

    }

    @Override
    public String getViewDataSetID() {
        return null;
    }

    @Override
    public void setViewDataSetColID(String s) {

    }

    @Override
    public String getViewDataSetColID() {
        return null;
    }

    @Override
    public void setValueDataSetColID(String s) {

    }

    @Override
    public String getValueDataSetColID() {
        return null;
    }

    @Override
    public Boolean getIsUserInternalDataSetID() {
        return null;
    }

    @Override
    public void setIsUserInternalDataSetID(Boolean aBoolean) {

    }

    @Override
    public String getIdentifier() {
        return null;
    }

    @Override
    public Object getPropertyMap() {
        return null;
    }

    @Override
    public void setPropertyMap(Object o) {

    }

    @Override
    public Object getProperty(String s, Object o) {
        return null;
    }

    @Override
    public void setProperty(String s, Object o) {

    }

    @Override
    public int getNumberPrecision() {
        return 0;
    }

    @Override
    public void seNumberPrecision(int i) {

    }

    @Override
    public String getNumberFormat() {
        return null;
    }

    @Override
    public void setNumberFormat(String s) {

    }

    @Override
    public String getColumnType() {
        return null;
    }

    @Override
    public void setColumnType(String s) {

    }

    @Override
    public String getEditorType() {
        return null;
    }

    @Override
    public void setEditorType(String s) {

    }

    @Override
    public String getDateFormat() {
        return null;
    }

    @Override
    public void setDateFormat(String s) {

    }

    @Override
    public String getFormulaOne() {
        return null;
    }

    @Override
    public void setFormulaOne(String s) {

    }

    @Override
    public String getEditMask() {
        return null;
    }

    @Override
    public void setEditMask(String s) {

    }

    @Override
    public String getFkeyID() {
        return null;
    }

    @Override
    public void setFkeyID(String s) {

    }

    @Override
    public String getRlglID() {
        return null;
    }

    @Override
    public void setRlglID(String s) {

    }

    @Override
    public void dataChanged(EFDataSet dataSet) {
        mainRowSet = dataSet.getCurrentRowSet();
        String url = "";
        if (mainRowSet != null) {
            url = mainRowSet.getString(dataSetColID, "");
        }
        if (!"".equals(url)) {
            GlideImageLoader.getInstance().displayImage(getContext(),signImage,url);
//            ImageLoader.getInstance().displayImage(url, signImage);
        } else {
            if (graffitiView != null)
                graffitiView.redo();
//            ImageLoader.getInstance().displayImage(null, signImage);
            signImage.setImageDrawable(getResources().getDrawable(R.drawable.form_sign_icon));

        }
    }

    @Override
    public String getDataSetID() {
        return dataSetID;
    }

    @Override
    public void setDataSet(EFDataSet dataSet) {
        if (this.dataSet != dataSet) {
            if (this.dataSet != null) this.dataSet.removeDataSetListener(this);
            this.dataSet = dataSet;
            if (this.dataSet != null) this.dataSet.addDataSetListener(this);
            this.dataChanged(dataSet);
        }
    }

    @Override
    public EFDataSet getDataSet() {
        return dataSet;
    }

    @Override
    public EFRowSet getMainRowSet() {
        return mainRowSet;
    }

    @Override
    public void dataSetChanged(DataSetEvent dataSetEvent) {
        dataChanged(dataSetEvent.getDataSet());

    }

    public interface SignListener {
        /**
         * 签名完成
         **/
        void onComplete(Bitmap bitmap);

        /**
         * 签名取消
         **/
        void onCancel();
    }

    public String getVerticalAlign() {
        return verticalAlign;
    }

    public void setVerticalAlign(String verticalAlign) {
        this.verticalAlign = verticalAlign;
    }

    public String getHorizontalAlign() {
        return horizontalAlign;
    }

    public void setHorizontalAlign(String horizontalAlign) {
        this.horizontalAlign = horizontalAlign;
    }

    public byte[] Bitmap2Bytes(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public void setBkgColor(int bkgColor) {
        this.bkgColor = bkgColor;

        this.setBackgroundColor(StringUtil.formColorToColor(bkgColor));
    }

    public int getBkgColor() {
        return bkgColor;
    }

    @Override
    public IUIComponent getParentComp() {
        return parentComp;
    }

    @Override
    public void setParentComp(IUIComponent comp) {
        parentComp = comp;
    }
}
